package com.scpii.api.common.auth.password;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.scpii.api.common.Constants;
import com.scpii.api.common.base.Response.Status;
import com.scpii.api.common.base.ResponseThreadlocal;
import com.scpii.api.domain.auth.UsersInfoDetails;
import com.scpii.api.domain.common.Field;
import com.scpii.api.domain.common.Field.FieldStatus;
import com.scpii.api.persistence.auth.UsersInfoDetailsMapper;
import com.scpii.api.persistence.common.FieldMapper;
import com.scpii.api.util.PrincipalUtil;

@Component
@Transactional
public class DefaultUsersInfoDetailsService implements UsersInfoDetailsService {

	@Resource
	private UsersInfoDetailsMapper usersInfoDetailsMapper;

	@Resource
	private FieldMapper fieldMapper;

	@Override
	public UserDetails loadUserInfoByUserName(String userName) {
		UsersInfoDetails userInfoDetails = usersInfoDetailsMapper
				.loadUserInfoDetailsByUserNameAndLoginTypes(PrincipalUtil
						.getPrincipal().getAppId(), userName,
						Constants.USER_PROVIDER_ARRAY);
		if (userInfoDetails == null) {
			throw new UsernameNotFoundException("username " + userName
					+ " not found ");
		}
		if (userInfoDetails.isAccountNonLocked() == true) {
			if (Constants.IS_LOGIN_FAILURE_LOCK) {
				int loginFailureLockTime = Constants.LOGIN_FAILURE_LOCK_TIME;
				if (loginFailureLockTime != 0) {

				}
			} else {

			}
		}
		if (!userInfoDetails.isEnabled()) {
			List<Field> fields = fieldMapper.selectAppExpandField(PrincipalUtil
					.getPrincipal().getAppId(),
					Constants.TABLE_PRIKARY_KEY_START_POSITION.get("USERS"),
					FieldStatus.ADD_REQUIRED_SHOW.getValue());
			if (fields != null
					&& fields.size() != 0
					&& ArrayUtils.contains(
							Constants.USERS_NON_ENABLE_TYPES_ARRY,
							userInfoDetails.getUserType())) {
				ResponseThreadlocal.getResponse().setStatus(
						Status.IMPROVE_USER_INFO);
			} else {
				userInfoDetails
						.setUserType(Constants.USERS_TYPES.get("NORMAL"));
			}
		}
		userInfoDetails.setLastLoginDt(new Date());
		userInfoDetails.setLastActivityDt(new Date());
		usersInfoDetailsMapper.updateByPrimaryKeySelective(userInfoDetails);
		return userInfoDetails;
	}

	@Override
	public UsersInfoDetails loadUsersInfoDetailsByPrimaryKey(Long id) {
		return usersInfoDetailsMapper.selectByPrimaryKey(id);
	}
}
